<template>
  <div class="app-container">
    <statistics-view v-hasPermi="['device:device:statistics']" v-if="queryParams.project"
      :state="pageSizetatisticsUpdate" :project="queryParams.project"
      :select-date="queryParams.selectDate"></statistics-view>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId" v-if="checkRole(['admin'])" label-width="44px">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable>
          <el-option v-for="(item,index) in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="project" label-width="44px">
        <el-select v-model="queryParams.project" placeholder="请选择项目" @change="handleChangeProject">
          <el-option v-for="(item,index) in projectOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备组" prop="deviceGroup">
        <el-select v-model="queryParams.deviceGroup" placeholder="请选择设备组" clearable multiple>
          <el-option v-for="(item,index) in deviceGroupOption" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="serviceState">
        <el-select v-model="queryParams.serviceState" placeholder="请选择服务状态" clearable>
          <el-option v-for="(item,index) in service_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="selectDate" @change="handleSelectDate">
        <el-date-picker v-model="queryParams.selectDate" type="date" :clearable="false" placeholder="请选择时间"
          value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item v-hasPermi="['device:device:query']">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5" v-hasPermi="['device:device:timer']">
        <el-select v-model="refreshTime" @change="handleRefreshTime">
          <el-option v-for="(item,index) in refresh_time" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-select v-model="deviceAction" placeholder="请选择命令" clearable @change="handleDeviceAction">
          <el-option v-for="(item,index) in device_action" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleConfigurationDialog">下发配置</el-button>
      </el-col>
      <template v-for="(item,index) in device_action" :key="item.value" >
        <el-col v-if="item.value >= 10" v-hasPermi="['device:device:command']" :span="1.5">
          <el-button type="primary" plain @click="handleDeviceAction(item.value)">{{item.label}}</el-button>
        </el-col>
      </template>
      <!-- <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('10')">开始脚本</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('11')">立即停止</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('12')">任务停止</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('13')">继续脚本</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('14')">暂停脚本</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('15')">亮屏</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:command']">
        <el-button type="primary" plain @click="handleDeviceAction('16')">息屏</el-button>
      </el-col> -->
      <el-col :span="1.5" v-hasPermi="['device:device:switch']">
        <el-button type="primary" plain @click="handleStopTimer">{{timer ? '暂停' : '开始'}}定时器</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:php']">
        <el-button type="primary" plain @click="handlePhpStatisticsDialogs">查看自定义统计</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['device:device:delete']">
        <el-button :disabled="!ids.length" type="danger" plain @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="setIntervalApi"
        v-hasPermi="['device:device:query']"></right-toolbar>
    </el-row>
    <div>
      <!-- tableHeight="900" -->
      <Table ref="pageTableRef" :table-data="tableData" :border="true" size="small" :loading="loading"
        :columns="columns" :is-pagination="true" :selection="true" :show-index="true" :total="total"
        :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" @changeSize="handleSizeChange"
        @changeCurrent="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
        <template #isScriptRunning="scope">
          <!-- {{scope.row.isScriptRunning}} -->
          <!-- <el-switch disabled :value="scope.row.isScriptRunning" class="ml-2" /> -->
          <el-tag v-if="scope.row.isScriptRunning" type="success">启动</el-tag>
          <el-tag v-else type="info">未启动</el-tag>
        </template>
      </Table>
    </div>
    <action-dialog ref="actionDialogs" v-if="actionDialogShow" @cancel="handleActionCancel"></action-dialog>
    <configuration-dialog ref="configurationDialogs" v-if="configurationDialogShow"
      @cancel="handleConfigurationDialogsCancel"></configuration-dialog>
    <php-statistics ref="phpStatisticsDialogs" v-if="phpStatisticsDialogsShow"></php-statistics>
  </div>
</template>

<script setup name="device">
  import { getSelectTypeList, devicesList, removeDevices } from "@/api/deviceManage/index.js";
  import actionDialog from './components/actionDialog.vue';
  import statisticsView from './components/statistics.vue';
  import configurationDialog from './components/configurationDialog.vue';
  import phpStatistics from './components/phpStatistics.vue';
  import { listUser } from "@/api/system/user";
  import { checkPermi, checkRole } from "@/utils/permission";
  const { proxy } = getCurrentInstance();
  const { device_action } = proxy.useDict('device_action'); // 设备操作
  const { service_status } = proxy.useDict('service_status'); // 服务状态
  const { refresh_time } = proxy.useDict('refresh_time'); // 刷新状态

  const tableData = ref([]);
  const open = ref(true);
  const buttonLoading = ref(false);
  const loading = ref(false);
  const actionDialogShow = ref(false);
  const configurationDialogShow = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const total = ref(0);
  const title = ref("");
  const timer = ref(null);
  const userList = ref([]);
  const tokenTable = ref();
  const pageSizetatisticsUpdate = ref(0);
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 200,
      project: '',
      deviceGroup: [],
      serviceState: [],
      selectDate: ''
    },
    rules: {
      // userId: [
      //   { required: true, message: "用户ID不能为空", trigger: "blur" }
      // ],
      // token: [
      //   { required: true, message: "不能为空", trigger: "blur" }
      // ],
      // expirationTime: [
      //   { required: true, message: "过期时间0不限制,1,2,3...,天数不能为空", trigger: "blur" }
      // ],
    }
  });
  const { queryParams, form, rules } = toRefs(data);
  // 循环获取项目/设备组
  const TypeList = ref([
    {
      type: 'project',
      selectDate: ''
    },
    {
      type: 'deviceGroup',
      selectDate: ''
    }
  ]);
  // 项目 下拉
  const projectOption = ref([]);
  // 设备组 下拉
  const deviceGroupOption = ref([]);
  // 刷新
  const refreshTime = ref('3000');
  // 服务状态
  const serviceStatus = ref('');
  // 设备操作
  const deviceAction = ref('');
  const actionDialogs = ref();
  const configurationDialogs = ref();
  const phpStatisticsDialogs = ref();
  const phpStatisticsDialogsShow = ref(false);
  const columns = ref([
    // {
    //   prop: 'id',
    //   label: 'ID',
    //   minWidth: 150,
    //   align: 'center',
    //   showOverflowTooltip: true,
    // },
    {
      prop: 'deviceName',
      label: '设备',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'project',
      label: '项目',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'deviceGroup',
      label: '设备组',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'battery',
      label: '电量',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'runtime',
      label: '运时',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'isScriptRunning',
      label: '状态',
      slot: 'isScriptRunning',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'date',
      label: '时间',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'lastUpdate',
      label: '更新时间',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
  ]);
  const firstAction = ref(true);
  function handleDelete() {
    const data = ids.value;
    const name = data.map(item => item.deviceName).join();
    const idArr = data.map(item => item.deviceId);
    proxy.$modal.confirm('是否确认删除"' + name + '"的设备？').then(function () {
      return removeDevices(idArr);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  }
  // 点击复制
  const handleCopy = (row) => {
    proxy.clickCopyFun(row);
  };
  function getCurrentDate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    var yyyy = today.getFullYear();
    return `${yyyy}-${mm}-${dd}`;
  }
  // queryParams.value.selectDate = getCurrentDate();
  /** 查询用户列表 */
  function getListUser() {
    listUser().then(res => {
      // console.log(res, 'ABCDEFG-getListUser');
      // loading.value = false;
      userList.value = res.rows;
      // total.value = res.total;
    });
  };
  if (checkRole(['admin'])) {
    getListUser();
  }
  getCurrentDate();
  function GetProjectTypeListApi() {
    getSelectTypeList({
      type: 'project',
      selectDate: queryParams.value.selectDate
    }).then(response => {
      projectOption.value = response.map((item) => {
        return {
          value: item.name,
          label: item.name,
          deviceIdList: item.deviceIdList
        };
      });
      queryParams.value.project = response[0].name;
      setTimeout(() => {
        GetDeviceGroupTypeListApi();
      });
    });
    // var today = new Date();
    // var dd = String(today.getDate()).padStart(2, '0');
    // var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    // var yyyy = today.getFullYear();
    // TypeList.value.forEach((element, idx) => {
    //   element.selectDate = `${yyyy}-${mm}-${dd}`;
    //   getSelectTypeList(element).then(response => {
    //     if (element.type == 'project') {
    //       if (response.length) {
    //         projectOption.value = response.map((item) => {
    //           return {
    //             value: item.name,
    //             label: item.name,
    //             deviceIdList: item.deviceIdList
    //           };
    //         });
    //         setTimeout(() => {
    //           queryParams.value.project = response[0].name;
    //         });
    //       }
    //     } else if (element.type == 'deviceGroup') {
    //       if (response.length) {
    //         deviceGroupOption.value = response.map((item) => {
    //           return {
    //             value: item.name,
    //             label: item.nameq,
    //             deviceIdList: item.deviceIdList
    //           };
    //         });
    //       }
    //     }
    //   });
    // });

  }
  function handleSelectDate(e) {
    // if(e) {
    //   GetProjectTypeListApi()
    // }
  }
  GetProjectTypeListApi();

  function handleChangeProject(e) {
    if (e) {
      setTimeout(() => {
        GetDeviceGroupTypeListApi();
      });
    }
  }

  function GetDeviceGroupTypeListApi() {
    getSelectTypeList({
      type: 'deviceGroup',
      project: queryParams.value.project,
      selectDate: queryParams.value.selectDate
    }).then(response => {
      deviceGroupOption.value = response.map((item) => {
        return {
          value: item.name,
          label: item.nameq,
          deviceIdList: item.deviceIdList
        };
      });
    });
  }
  function handlePhpStatisticsDialogs() {
    let data = {
      project: queryParams.value.project,
      selectDate: queryParams.value.selectDate,
      deviceGroup: queryParams.value.deviceGroup
    };
    phpStatisticsDialogsShow.value = true;
    setTimeout(() => {
      phpStatisticsDialogs.value.openDialog(data);
    }, 100);

  }
  function handleActionCancel() {
    actionDialogShow.value = false;
    deviceAction.value = '';
  }
  function handleConfigurationDialogsCancel() {
    configurationDialogShow.value = false;
  }
  function handleConfigurationDialog() {
    // console.log(event, 'ABCDEFG-handleDeviceAction');
    let data = {
      // deviceAction: event,
      project: queryParams.value.project,
      selectDate: queryParams.value.selectDate,
      userId: queryParams.value.userId
    };
    configurationDialogShow.value = true;
    setTimeout(() => {
      configurationDialogs.value.openDialog(data);
    }, 100);
  }
  function handleDeviceAction(event) {
    // console.log(event, 'ABCDEFG-handleDeviceAction');
    let data = {
      deviceAction: event,
      project: queryParams.value.project,
      selectDate: queryParams.value.selectDate,
    };
    actionDialogShow.value = true;
    setTimeout(() => {
      startOpen(data);
    }, 100);
  }
  function startOpen(row) {
    actionDialogs.value.openDialog(row);
    // console.log(actionDialogs.value.openDialog(), 'ABCDEFG-actionDialog');

  }
  /** 查询用户token列表 */
  function getList() {
    // loading.value = true;
    let query = JSON.parse(JSON.stringify(queryParams.value));
    query.deviceGroup = query.deviceGroup ? query.deviceGroup.join() : '';
    // console.log(query, 'ABCDEFG-query');

    devicesList(query).then(response => {
      let list = response.rows || [];
      if (list.length) {
        let findIdx = 0;
        list.forEach((item, index) => {
          item.newColumns = item.columns ? JSON.parse(item.columns) : [];
          item.transformedData = [];
          item.newColumns.forEach((items, indexs) => {
            // 使用Object.entries方法遍历对象的每个属性
            // 创建新对象
            const newItem = {
              prop: 'newColumns' + indexs,
              label: items.label,
              align: 'center',
            };
            item.transformedData.push(newItem);
            item['newColumns' + indexs] = String(items.value);
          });
          if (item.newColumns.length > findIdx) {
            findIdx = index;
          }
        });
        // console.log(findIdx, 'ABCDEFG-findIdx');
        // console.log(list, 'ABCDEFG-list');
        let insertPosition = 3; // 假设在索引1的位置插入
        let newColumns = [{
          prop: 'deviceName',
          label: '设备',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'project',
          label: '项目',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'deviceGroup',
          label: '设备组',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'battery',
          label: '电量',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'runtime',
          label: '运时',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'isScriptRunning',
          label: '状态',
          slot: 'isScriptRunning',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'date',
          label: '时间',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'lastUpdate',
          label: '更新时间',
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
        },];
        newColumns.splice(insertPosition, 0, ...list[findIdx].transformedData); // 在指定位置插入arr2的所有元素
        // console.log(newColumns);

        columns.value = newColumns;
        firstAction.value = false;
      }
      tableData.value = list;
      total.value = response.total;
      pageSizetatisticsUpdate.value++;
      if (queryParams.value.selectDate) {
        if (getCurrentDate() !== queryParams.value.selectDate) {
          // console.log(4567);
          clearInterval(timer.value);
          timer.value = null;
        }
      }
      // loading.value = false;
    });
  }

  // 表单重置
  function reset() {
    // var today = new Date();
    // var dd = String(today.getDate()).padStart(2, '0');
    // var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    // var yyyy = today.getFullYear();
    queryParams.value.pageNum = 1;
    queryParams.value.pageSize = 100;
    queryParams.value.deviceGroup = '';
    queryParams.value.serviceState = [];
    queryParams.value.selectDate = '';
    // proxy.resetForm("queryRef");
    queryParams.value.project = projectOption.value.value;
    pageSizetatisticsUpdate.value = 0;
    setIntervalApi();
    GetProjectTypeListApi();
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    setIntervalApi();
    GetProjectTypeListApi();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    // var today = new Date();
    // var dd = String(today.getDate()).padStart(2, '0');
    // var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    // var yyyy = today.getFullYear();
    queryParams.value.pageNum = 1;
    queryParams.value.pageSize = 100;
    queryParams.value.deviceGroup = '';
    queryParams.value.serviceState = [];
    queryParams.value.selectDate = '';
    // proxy.resetForm("queryRef");
    queryParams.value.project = projectOption.value[0].value;
    handleQuery();
  }
  const handleSizeChange = (val) => {
    queryParams.value.pageSize = val;
    getList();
  };
  const handleCurrentChange = (val) => {
    // console.log(val,'ABCDEFG-handleCurrentChange');
    queryParams.value.pageNum = val;
    // console.log(queryParams.value, 'ABCDEFG-queryParams.value');
    getList();
  };
  const handleSelectionChange = (selection) => {
    let idList = selection.map(item => {
      return {
        deviceId: item.deviceId,
        deviceName: item.deviceName
      };
    });
    ids.value = idList;
    // console.log(ids.value);
  };
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["userTokenRef"].validate(valid => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.userId != null) {
          updateUserToken(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }).finally(() => {
            buttonLoading.value = false;
          });
        } else {
          addUserToken(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }).finally(() => {
            buttonLoading.value = false;
          });
        }
      }
    });
  }
  function handleStopTimer() {
    if (timer.value) {
      clearInterval(timer.value);
      timer.value = null;
    } else {
      setIntervalApi();
    }
  }
  function handleStartTimer() {
    setIntervalApi();
  }
  function handleRefreshTime(e) {
    clearInterval(timer.value);
    setIntervalApi();
  }
  function setIntervalApi() {
    clearInterval(timer.value);
    if (queryParams.value.selectDate == '') {
      timer.value = setInterval(() => {
        getList();
      }, refreshTime.value);
    } else {
      if (getCurrentDate() !== queryParams.value.selectDate) {
        clearInterval(timer.value);
        timer.value = null;
        getList();
      } else {
        timer.value = setInterval(() => {
          getList();
        }, refreshTime.value);
      }
    }
  }
  if (checkPermi(['device:device:query'])) {
    setIntervalApi();
  }
  onUnmounted(() => {
    clearInterval(timer.value);
    timer.value = null;
  });
</script>
<style lang="scss" scoped>
  :deep(.modal-wrap) {
    pointer-events: none !important;
  }

  .el-row {
    margin-bottom: 20px;
  }

  .el-row:last-child {
    margin-bottom: 0;
  }

  .el-col {
    border-radius: 4px;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 120px;
    border: 1px solid #f0f0f0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, .15);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    /* background: yellowgreen; */
    /* padding: 12px; */
  }

  .grid-content-top {
    display: flex;
    justify-content: center;
    flex-direction: column;
    min-height: 56px;
    margin-bottom: -1px;
    padding: 0 24px;
    color: rgba(0, 0, 0, 0.88);
    font-weight: 600;
    font-size: 16px;
    border-bottom: 1px solid #f0f0f0;
    border-radius: 8px 8px 0 0;
  }

  .grid-content-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .grid-content-bottom {
    padding: 12px;
  }

  .grid-content-item {
    padding-top: 1rem;
    padding-bottom: 1rem;
    padding-left: 1rem;
    padding-right: 1rem;
    display: flex;
    align-items:
      center;
    justify-content: space-between;
  }

  .grid-content-items {
    padding: 0.5rem;
    display: flex;
    align-items: center;
    padding-left: 1rem;
    padding-right: 1rem;
    justify-content: space-between;
  }

  /*
  :deep() {
    .el-dialog {
      pointer-events: auto !important;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  } */
</style>
